#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using TVC.Layout;
using System.Xml;
using System.IO;
using BUS;
using DTO;
using DAO;
using System.Text.RegularExpressions;
#endregion

namespace TVC.Modules.Business
{
    public partial class InvoiceRegister : ModuleParent, IHostedApplication
    {
        //int idAllowEditLanguage = 1;
        int idAddNew = 166,
            idEdit = 167,
            idDelete = 224,
            idPrint = 168,
            idUpdate = 169,
            idTransmit = 170,
            idReturn = 171,
            idSplit = 172,
            idArgingReport = 212,
            idInvoiceStatus = 213,
            idDeliveryNote = 214,
            idReturnToAP = 215;
        int idToExcel = 259;


        int _oldPeriod = 0;
        bool _isCalculate = true;
        string _oldContract = string.Empty;
        public InvoiceRegister()
        {
            InitializeComponent();
            _strType = "Invoice";
            _dgvList = dgvInvoiceRegister;
            _dgvFilter = gridFilter1;
            InitPopup();

        }
        private void InitPopup()
        {
            txtDescription.LabelField = lbDescription;
            txtRemark1.LabelField = lbRemark1;
            txtRemark2.LabelField = lbRemark2;
            txtRemark3.LabelField = lbRemark3;
            txtDescription.Button = btDesc;
            txtRemark1.Button = btRemark1;
            txtRemark2.Button = btRemark2;
            txtRemark3.Button = btRemark3;
        }

        public void InitializeApplication()
        {

        }

        public void SetObject(object obj)
        {
        }

        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Add New", "New", new IconResourceHandle("Add.png"), "C"));
            if (IsPermis(idAddNew) && IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Save", "Save", new IconResourceHandle("Save.png"), "S", false));
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Copy", "Copy", new IconResourceHandle("Copy.gif"), "O"));
            if (IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Edit", "Edit", new IconResourceHandle("Edit.png"), "A"));
            if (IsPermis(idDelete)) objElements.Add(new HostedToolBarButton("Delete", "Delete", new IconResourceHandle("Delete.png"), "X"));
            objElements.Add(new HostedToolBarButton("Skip", "Skip", new IconResourceHandle("Reject.png"), "K", false));
            if (IsPermis(idUpdate)) objElements.Add(new HostedToolBarButton("Update", "Update", new IconResourceHandle("up.png"), "U"));
            if (IsPermis(idTransmit)) objElements.Add(new HostedToolBarButton("Transmit", "Transmit", new IconResourceHandle("Next.png"), "T"));
            if (IsPermis(idReturn)) objElements.Add(new HostedToolBarButton("Return", "Return", new IconResourceHandle("Back.gif"), "N"));
            if (IsPermis(idSplit)) objElements.Add(new HostedToolBarButton("Split", "Split", new IconResourceHandle("Split.png"), "L"));
            if (IsPermis(idToExcel)) objElements.Add(new HostedToolBarButton("To excel", "To excel", new IconResourceHandle("Excel.png"), "P"));
            if (IsPermis(idArgingReport)) objElements.Add(new HostedToolBarButton("AgingReport", "Aging Report", new IconResourceHandle("Print.png"), "AR"));
            if (IsPermis(idInvoiceStatus)) objElements.Add(new HostedToolBarButton("InvoiceStatus", "Invoice Status", new IconResourceHandle("Method.gif"), "IR"));
            if (IsPermis(idDeliveryNote)) objElements.Add(new HostedToolBarButton("DeliveryNote", "Delivery Note", new IconResourceHandle("ShowLines.gif"), "DR"));
            if (IsPermis(idReturnToAP)) objElements.Add(new HostedToolBarButton("ReturnToAP", "Return To A/P", new IconResourceHandle("Back.gif"), "RR"));

            objElements.Add(new HostedToolBarButton("Refresh", "Refresh", new IconResourceHandle("Refresh.png"), "R"));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }
        protected override void SetupToolBar(string strAction)
        {
            ToolBar tbarLocal = GetTbarLocal();
            bool on = true, off = false;
            if (tbarLocal == null) return;

            switch (strAction)
            {
                case "C":
                case "O":
                case "A":
                    foreach (ToolBarButton button in tbarLocal.Buttons)
                    {
                        if (button.Name == "R" || button.Name == "AR" || button.Name == "IR" || button.Name == "RR" || button.Name == "DR" || button.Name == "P")
                            button.Enabled = on;
                        else if (!_btnProcess.Contains(button.Name))
                        {
                            if (button.Enabled != off) button.Enabled = off;
                        }
                        else { if (button.Enabled != on) button.Enabled = on; }
                    }
                    break;
                default:
                    foreach (ToolBarButton button in tbarLocal.Buttons)
                    {
                        if (button.Name == "R" || button.Name == "AR" || button.Name == "IR" || button.Name == "RR" || button.Name == "DR" || button.Name == "P")
                            button.Enabled = on;
                        else if (!_btnProcess.Contains(button.Name))
                        {
                            if (button.Enabled != on) button.Enabled = on;
                        }
                        else { if (button.Enabled != off) button.Enabled = off; }
                    }

                    break;
            }

        }
        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            string busId = GetMainForm().PODInfo.Business_ID;
            Cancel = false;
            try
            {
                sErr = "";
                string strAction = (string)objButton.Tag;

                switch (strAction)
                {
                    case "C":
                        AddNew(txtInvNo);
                        txtYear.Value = DateTime.Now.Year;
                        break;
                    case "U":
                        ShowUpdate();
                        break;
                    case "A":
                        editRecord(txtReference);
                        break;
                    case "S":
                        saveRecord(txtInvNo);
                        break;
                    case "O":
                        copy(txtInvNo);
                        break;
                    case "X":
                        delete(txtReference);
                        break;
                    case "K":
                        skip();
                        break;
                    case "T":
                        ShowTranmit();
                        break;
                    case "L":
                        ShowSplit();
                        break;
                    case "N":
                        ShowReturn();
                        break;
                    case "R":
                        RefreshInvoice();
                        break;
                    case "AR":
                        GetMainForm().SelectCategory("QRS", "id=AgingRpt01_" + busId, objButton.Text);
                        break;
                    case "DR":
                        GetMainForm().SelectCategory("QRS", "id=DeliveryNote_" + busId, objButton.Text);
                        break;
                    case "IR":
                        GetMainForm().SelectCategory("QRS", "id=InvStatus01_" + busId, objButton.Text);
                        break;
                    case "RR":
                        GetMainForm().SelectCategory("QRS", "id=ReturnNote_" + busId, objButton.Text);
                        break;
                    case "P":
                        export2Excel();
                        break;
                }

                if (sErr == "") ThrowMsg("Command: " + strAction);

            }
            catch (Exception ex)
            {
                ThrowMsg(ex.Message + Environment.NewLine + ex.Source);
            }
        }


        #region .::| Override Functions |::.

        protected override ErrorStatus validateForm(ref string sErr)
        {
            ErrorStatus result = ErrorStatus.SUCCESS;
            sErr = "";
            string sWarn = "";
            CheckInvNo();
            CheckPayRef();
            CheckReceiDate();
            CheckVendorCode();
            CheckVendorType();
            CheckContractCode();
            CheckBudgetCode();
            CheckIssueDate();
            CheckCurrency();
            CheckOurRef();
            CheckValue();
            // CheckContractValue();
            CheckPayableAmt();


            foreach (Control x in gbPrimary.Controls)
            {
                if (x.Tag != null && x.Tag.ToString() == "Warning") { if (warnProvider.GetError(x) != string.Empty) sWarn += string.Format("Warning: {0}\n", warnProvider.GetError(x)); }
                else { if (errProvider.GetError(x) != string.Empty) sErr += string.Format("Error: {0}\n", errProvider.GetError(x)); }
            }

            if (sErr != "") result = ErrorStatus.ERROR;
            else if (sWarn != "") result = ErrorStatus.WARNING;

            sErr = string.Format("{0}{1}", sErr, sWarn);

            return result;
        }
        protected override bool checkExists()
        {
            InvoiceRegisterControl ctr = new InvoiceRegisterControl();
            string BusId = GetMainForm().PODInfo.Business_ID;
            Int16 line = txtLineNo.Text == "" ? Convert.ToInt16(-1) : Convert.ToInt16(txtLineNo.Text);
            int refer = txtReference.Text == "" ? Convert.ToInt32(-1) : Convert.ToInt32(txtReference.Text);
            bool exists = ctr.IsExist(refer, line);
            if (BusId == "HV") exists = ctr.IsExist1(refer, line);
            if (exists == false) return false;

            if (BusId == "HL") return ctr.IsExist_InvoiceRegister(txtInvNo.Text, cboVendor.Value.ToString(), line);
            return ctr.IsExist_InvoiceRegister1(txtInvNo.Text, cboVendor.Value.ToString(), line);

        }

        protected override string addRecord(bool isDraft = false)
        {
            string sErr = "";
            InvoiceRegisterControl ctr = new InvoiceRegisterControl();
            InvoiceRegisterInfo inf = GetData();
            inf.Reference = Convert.ToInt32(ctr.getNextRef(ref sErr, GetMainForm().PODInfo.Business_ID));
            inf.LineNo = 1;
            int refer = ctr.add(GetMainForm().PODInfo.Business_ID, inf, ref sErr);
            if (sErr == "")
            {
                txtReference.Text = inf.Reference.ToString();
                txtLineNo.Text = inf.LineNo.ToString();
                _oldPeriod = inf.Period;
            }
            return sErr;
        }
        protected override string updateRecord(bool isDraft = false)
        {
            InvoiceRegisterControl ctr = new InvoiceRegisterControl();
            InvoiceRegisterInfo info = GetData();
            return ctr.update(GetMainForm().PODInfo.Business_ID, info);
        }
        protected override string delRecord()
        {
            InvoiceRegisterControl ctr = new InvoiceRegisterControl();
            int Reference = (txtReference.Text == "" ? -1 : int.Parse(txtReference.Text));
            short LineNo = (txtLineNo.Text == "" ? (short)-1 : short.Parse(txtLineNo.Text));
            return ctr.Delete(GetMainForm().PODInfo.Business_ID, Reference, LineNo);
        }

        protected override void copy(Control keyControl)
        {
            MessageBox.Show("Do you want to copy from the " + keyControl.Text + " record?", "Copy", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
            {
                if (((MessageBoxWindow)newSender).DialogResult != DialogResult.OK)
                {
                    _processStatus = "C";
                    refreshForm("");
                }
                else
                {
                    txtReference.Text = "";
                    txtAccRef.Text = "";
                    txtInvNo.Text = "";
                    txtLineNo.Text = "";

                    txtPaymentDate.Value = DateTime.MinValue;
                    txtPaymentRef.Text = "";
                    txtDeliveryDate.Value = DateTime.MinValue;
                    txtReturnedDate.Value = DateTime.MinValue;
                    //cboBudgetCode.SelectedValue = "";
                    //txtYear.Value = 0;

                    _processStatus = "O";
                }

                SetupToolBar(_processStatus);
                enableForm(true);
                keyControl.Focus();
            }, false);
        }

        protected override ErrorStatus beforeUpdate(ref string sErr)
        {
            int newPeriod = Convert.ToInt32(txtPeriod.Text);
            if (newPeriod != _oldPeriod)
            {
                sErr = "Check Receive Date, please!";
                return ErrorStatus.ERROR;
            }

            return ErrorStatus.SUCCESS;
        }

        protected override void afterUpdate()
        {
            UpdateTotalBudget();
            UpdateTotalContract();
            if (!string.IsNullOrEmpty(_oldContract) && _oldContract != cboContractPO.Value + "") UpdateTotalContract(_oldContract);
            LoadTotalBudget();
            LoadTotalContract();
            LoadTotalInv();
        }
        protected override void afterAddNew()
        {
            UpdateTotalBudget();
            UpdateTotalContract();
            //if (!string.IsNullOrEmpty(_oldContract)) UpdateTotalContract(_oldContract);
            LoadTotalBudget();
            LoadTotalBudget();
            LoadTotalContract();
            LoadTotalInv();

        }
        protected override void afterDelete()
        {
            UpdateTotalBudget();
            UpdateTotalContract();
            //if (!string.IsNullOrEmpty(_oldContract)) UpdateTotalContract(_oldContract);
            LoadTotalBudget();
            LoadTotalContract();
            LoadTotalInv();
        }
        public void RefreshInvoice()
        {
            LoadTotalBudget();
            LoadTotalContract();
            LoadTotalInv();
            LoadCombo();

        }
        protected override void refreshForm(string str)
        {
            _isCalculate = false;
            gbPrimary.SuspendLayout();
            txtReference.Text = str;
            txtInvNo.Text = str;
            txtLineNo.Text = str;

            txtAccRef.Text = str;
            txtIssuedDate.Text = str;
            txtReceivedDate.Text = str;
            txtAmount.Value = 0;
            txtOtherAmount.Value = 0;
            txtCurrency.Text = str;

            txtDueDate.Text = str;
            txtDescription.Text = str;
            cboContractPO.Value = str;
            txtDeliveryDate.Text = str;
            txtReturnedDate.Text = str;
            txtDepartmentHeld.Text = str;
            txtRemark1.Text = str;
            txtRemark2.Text = str;
            txtRemark3.Text = str;
            //mark 
            //tranmisref
            //tranmisdate
            //marktrm
            //tranmisstat
            //recv
            cboVendor.Value = str;
            cboCreditor.Text = str;
            txtLineNo.Text = str;
            txtRate.Value = 0;
            // return ref
            txtReturnedDate.Text = str;
            cboBudgetCode.SelectedValue = str;
            txtVAT.Value = 0;
            txtVATOther.Value = 0;
            txtVATper.Value = 0;
            txtExpenseAmt.Value = 0;
            cboVendorType.SelectedValue = str;
            txtCIT.Value = 0;
            txtPayableAmt.Value = 0;
            txtPaymentRef.Text = str;

            txtPaymentDate.Text = str;
            //bussiness
            txtPeriod.Text = str;
            _oldPeriod = 0;
            txtPaymTerm.Text = str;
            txtYear.Value = 0;
            //status
            //vou
            //acct
            //invsn
            //employ
            //create
            //modifi
            //createDate
            //Modif
            txtIssuedDate.Value = DateTime.MinValue;
            txtReceivedDate.Value = DateTime.MinValue;
            txtDueDate.Value = DateTime.MinValue;
            txtPaymentDate.Value = DateTime.MinValue;
            txtReceivedDate.Value = DateTime.MinValue;
            txtDeliveryDate.Value = DateTime.MinValue;
            txtReturnedDate.Value = DateTime.MinValue;
            txtYear.Value = 0;
            txtPayableAmtOther.Value = 0;
            _oldContract = string.Empty;
            gbPrimary.ResumeLayout(true);
            _isCalculate = true;
        }
        protected override void enableForm(bool val)
        {
            gbPrimary.SuspendLayout();
            if (txtInvNo.Enabled != val) txtInvNo.Enabled = val;

            if (txtAccRef.Enabled != val) txtAccRef.Enabled = val;
            if (txtIssuedDate.Enabled != val) txtIssuedDate.Enabled = val;
            if (txtReceivedDate.Enabled != val) txtReceivedDate.Enabled = val;
            if (txtAmount.Enabled != val) txtAmount.Enabled = val;
            if (txtOtherAmount.Enabled != val) txtOtherAmount.Enabled = val;
            if (txtCurrency.Enabled != val) txtCurrency.Enabled = val;
            if (btBudget.Enabled != val) btBudget.Enabled = val;
            if (txtDueDate.Enabled != val) txtDueDate.Enabled = val;
            if (txtDescription.Enabled != val) txtDescription.Enabled = val;
            //cboContractPO.Value = info.Contract;
            if (txtDeliveryDate.Enabled != val) txtDeliveryDate.Enabled = val;
            if (txtReturnedDate.Enabled != val) txtReturnedDate.Enabled = val;
            if (txtDepartmentHeld.Enabled != val) txtDepartmentHeld.Enabled = val;
            if (txtRemark1.Enabled != val) txtRemark1.Enabled = val;
            if (txtRemark2.Enabled != val) txtRemark2.Enabled = val;
            if (txtRemark3.Enabled != val) txtRemark3.Enabled = val;
            if (txtPaymentRef.Enabled != val) txtPaymentRef.Enabled = val;
            if (txtYear.Enabled != val) txtYear.Enabled = val;
            //mark 
            //tranmisref
            //tranmisdate
            //marktrm
            //tranmisstat
            //recv
            if (cboVendor.Enabled != val) cboVendor.Enabled = val;
            if (cboCreditor.Enabled != val) cboCreditor.Enabled = val;
            if (cboContractPO.Enabled != val) cboContractPO.Enabled = val;
            if (cboVendorType.Enabled != val) cboVendorType.Enabled = val;
            // txtLineNo.Enabled = val;
            if (txtRate.Enabled != val) txtRate.Enabled = val;
            // return ref
            if (txtReturnedDate.Enabled != val) txtReturnedDate.Enabled = val;
            if (cboBudgetCode.Enabled != val) cboBudgetCode.Enabled = val;
            if (txtVAT.Enabled != val) txtVAT.Enabled = val;
            if (txtVATOther.Enabled != val) txtVATOther.Enabled = val;
            if (txtVATper.Enabled != val) txtVATper.Enabled = val;
            // txtExpenseAmt.Enabled = val;
            //ori
            if (txtCIT.Enabled != val) txtCIT.Enabled = val;
            // txtPayableAmt.Enabled = val;
            // txtPaymentRef.Enabled = val;

            if (txtPaymentDate.Enabled != val) txtPaymentDate.Enabled = val;
            //bussiness
            // txtPeriod.Enabled = val;
            if (txtPaymTerm.Enabled != val) txtPaymTerm.Enabled = val;
            //  txtYear.Enabled = val;
            if (val == false)
            {
                foreach (Control x in gbPrimary.Controls)
                {
                    if (errProvider.GetError(x) != string.Empty) errProvider.SetError(x, "");
                }
            }
            gbPrimary.ResumeLayout(true);
        }

        protected override void loadRecord(object o)
        {
            if (o is DataRowView)
            {
                DTO.InvoiceRegisterInfo inf = new InvoiceRegisterInfo((DataRowView)o);
                SetData(inf);
            }
        }

        #endregion .::| Override Functions |::.


        private void InvoiceRegister_Load(object sender, EventArgs e)
        {
            LoadCombo();
            refreshForm("");
            enableForm(false);
            _processStatus = "V";
        }

        private void LoadCombo()
        {
            DataTable dtb = new DataTable();

            dtb.Columns.Add("ID", typeof(string));
            dtb.Columns.Add("Name", typeof(string));
            dtb.Rows.Add("D", "Domestic");
            dtb.Rows.Add("F", "Foreign");
            dtb.Rows.Add("H", "History");
            var o = cboVendorType.SelectedValue;
            cboVendorType.DataSource = dtb;
            cboVendorType.DisplayMember = "Name";
            cboVendorType.ValueMember = "ID";
            if (o != null) cboVendorType.SelectedValue = o;
            //VENDOR CODE

            BUS.VENDORControl ctrVD = new BUS.VENDORControl();
            DataTable dtbVD = new DataTable();
            dtbVD = ctrVD.GetAll_VENDOR(ref sErr);
            o = cboVendor.Value;
            cboVendor.MainForm = GetMainForm();
            cboVendor.Lookup = "VendorCode";
            cboVendor.DisplayMember = "VendorCode";
            cboVendor.ValueMember = "VendorCode";
            cboVendor.DataSource = dtbVD;
            if (o != null) cboVendor.Value = o;

            // CREDIA
            o = cboCreditor.Text;
            cboCreditor.DisplayMember = "VendorName";
            cboCreditor.ValueMember = "VendorName";
            cboCreditor.MainForm = GetMainForm();
            cboCreditor.Lookup = "VendorCode";
            cboCreditor.DataSource = dtbVD;
            if (o != null) cboCreditor.Text = o + "";
            //CONTRACT PO NOD
            DataTable _dtContract = null;
            BUS.ContractControl ctrcontract = new BUS.ContractControl();

            if (GetMainForm().PODInfo.Business_ID == "HL") _dtContract = ctrcontract.GetAll_Contract(ref sErr);
            else _dtContract = ctrcontract.GetAll_Contract1(ref sErr);
            o = cboContractPO.Value;
            cboContractPO.DisplayMember = "Contract";
            cboContractPO.ValueMember = "Contract";
            cboContractPO.MainForm = GetMainForm();
            cboContractPO.Lookup = "cboCTPO";
            cboContractPO.DataSource = _dtContract;
            if (o != null) cboContractPO.Value = o;

            //BUDGET CODE 
            BUS.BudgetsControl ctrcontr = new BUS.BudgetsControl();
            o = cboBudgetCode.SelectedValue;
            cboBudgetCode.DisplayMember = "BudgetCode";
            cboBudgetCode.ValueMember = "BudgetCode";

            cboBudgetCode.DataSource = ctrcontr.GetShortAll(GetMainForm().PODInfo.Business_ID, ref sErr);
            if (o != null) cboBudgetCode.SelectedValue = o;
            btBudget.Tag = ctrcontr.GetAll(GetMainForm().PODInfo.Business_ID, ref sErr);
        }

        private void gridFilter1_GridFiterEvent(string strFilter, int year)
        {
            string sErr = "";
            InvoiceRegisterControl ivCtr = new InvoiceRegisterControl();
            FormatDate();
            DataTable dtb = ivCtr.GetCond(GetMainForm().PODInfo.Business_ID, strFilter, ref sErr);
            if (!string.IsNullOrEmpty(sErr))
            {
                MessageBox.Show(sErr, "The filter is not valid");
                return;
            }
            dgvInvoiceRegister.SuspendLayout();
            if (!string.IsNullOrEmpty(gridFilter1.SortField))
            {
                dtb.DefaultView.Sort = gridFilter1.SortField + " " + gridFilter1.Direction;
            }
            bisInvoiceRegister.DataSource = dtb;

            dgvInvoiceRegister.ResumeLayout(true);
            if (dtb.Rows.Count > 0)
            {
                try
                {
                    object PayableAmtOther = dtb.Compute("SUM(PayableAmtOther)", "");
                    object PayableAmt = dtb.Compute("SUM(PayableAmt)", "");

                    txtTotalPayable.Value = PayableAmt == DBNull.Value ? 0 : Convert.ToDecimal(PayableAmt);
                    txtTotalOtherPayable.Value = PayableAmtOther == DBNull.Value ? 0 : Convert.ToDecimal(PayableAmtOther);
                }
                catch { }
            }
            else
            {
                txtTotalPayable.Value = 0;
                txtTotalOtherPayable.Value = 0;
            }

        }

        private void SetData(InvoiceRegisterInfo info)
        {
            gbPrimary.SuspendLayout();
            _isCalculate = false;
            txtReference.Text = info.Reference.ToString();
            txtInvNo.Text = info.InvNo;
            txtInvNo.Tag = info;

            txtAccRef.Text = info.OurRef;
            txtIssuedDate.Text = info.IssueDate.ToString("dd/MM/yyyy");
            txtReceivedDate.Text = info.ReceiptDate.ToString("dd/MM/yyyy");
            txtAmount.Value = (decimal)info.Amt;
            txtOtherAmount.Value = (decimal)info.OtherAmt;
            txtCurrency.Text = info.Currency.ToString();

            txtDueDate.Text = info.DueDate.ToString("dd/MM/yyyy");
            txtDescription.Text = info.Description.ToString();
            cboContractPO.Value = _oldContract = info.Contract;
            if (cboContractPO.SelectedItem is DataRowView)
                chkUncheckI.Checked = ((DataRowView)cboContractPO.SelectedItem)["SharedContract"].ToString() != "0";
            txtDeliveryDate.Text = info.DeliveryDate.ToString("dd/MM/yyyy");
            txtReturnedDate.Text = info.ReturnedDate.ToString("dd/MM/yyyy");
            txtDepartmentHeld.Text = info.Department.ToString();
            txtRemark1.Text = info.Remark1;
            txtRemark2.Text = info.Remark2;
            txtRemark3.Text = info.Remark3;
            //mark 
            //tranmisref
            //tranmisdate
            //marktrm
            //tranmisstat
            //recv
            cboVendor.Value = info.VendorCode;
            cboCreditor.Text = info.Creditor.ToString();
            txtLineNo.Text = info.LineNo.ToString();
            txtRate.Value = (decimal)info.CvtRate;
            // return ref
            txtReturnedDate.Text = info.ReturnedDate.ToString("dd/MM/yyyy");
            cboBudgetCode.SelectedValue = info.Budget;// ???
            txtVAT.Value = (decimal)info.VAT;
            txtVATOther.Value = (decimal)info.VATOther;
            txtVATper.Value = (decimal)info.VATPercent;
            txtExpenseAmt.Value = (decimal)info.ExpenseAmt;
            cboVendorType.SelectedValue = info.Originality;
            txtCIT.Value = (decimal)info.CIT;
            txtPayableAmt.Value = (decimal)info.PayableAmt;
            txtPaymentRef.Text = info.PymtRef.ToString();
            txtPayableAmtOther.Value = (decimal)info.PayableAmtOther;
            txtPaymentDate.Text = info.PaidDate.ToString("dd/MM/yyyy");
            //bussiness
            txtPeriod.Text = info.Period == -1 || info.Period == 0 ? "" : info.Period.ToString();
            _oldPeriod = info.Period;
            txtPaymTerm.Text = info.PaymentTerm == -1 ? "" : info.PaymentTerm.ToString();
            txtYear.Value = (decimal)info.aYear;
            //status
            //vou
            //acct
            //invsn
            //employ
            //create
            //modifi
            //createDate
            //Modif
            LoadTotalBudget();
            LoadTotalContract();
            LoadTotalInv();
            _isCalculate = true;
            gbPrimary.ResumeLayout(true);
        }
        private InvoiceRegisterInfo GetData()
        {
            InvoiceRegisterInfo old = (InvoiceRegisterInfo)txtInvNo.Tag;
            string payTem = txtPaymTerm.Text;

            // string creditor = txtCreditor.Text;
            if (!Regex.IsMatch(payTem, "^[0-9]+$")) payTem = "0";
            InvoiceRegisterInfo info = new InvoiceRegisterInfo()
            {
                Reference = (txtReference.Text == "" ? -1 : int.Parse(txtReference.Text)),
                LineNo = (txtLineNo.Text == "" ? (short)-1 : short.Parse(txtLineNo.Text)),
                InvNo = txtInvNo.Text,
                ACCNT_CODE = "",
                Amt = Math.Round((double)txtAmount.Value, txtAmount.DecimalPlaces),
                aYear = Convert.ToInt16(txtYear.Value),
                Budget = cboBudgetCode.SelectedValue + "",
                Business = GetMainForm().PODInfo.Business_ID,
                CIT = Math.Round(Convert.ToDouble(txtCIT.Value), txtCIT.DecimalPlaces),
                Contract = cboContractPO.Value.ToString(),
                CreatedBy = GetMainForm().PODInfo.USER_ID,
                CreatedDate = DateTime.Now,
                Creditor = cboCreditor.Text,
                Currency = txtCurrency.Text,
                CvtRate = Math.Round(Convert.ToDouble(txtRate.Value), txtRate.DecimalPlaces),
                DeliveryDate = txtDeliveryDate.Value,
                Department = txtDepartmentHeld.Text,
                Description = txtDescription.Text,
                DueDate = txtDueDate.Value,
                ExpenseAmt = Math.Round(Convert.ToDouble(txtExpenseAmt.Value), txtExpenseAmt.DecimalPlaces),
                //InvSN 
                IssueDate = txtIssuedDate.Value,
                //LineNo = 
                ModifiedBy = GetMainForm().PODInfo.USER_ID,
                ModifiedDate = DateTime.Now,
                Originality = string.Format("{0}", cboVendorType.SelectedValue),
                OtherAmt = Math.Round(Convert.ToDouble(txtOtherAmount.Value), txtOtherAmount.DecimalPlaces),
                OurRef = txtAccRef.Text,
                PaidDate = txtPaymentDate.Value,
                PayableAmt = Math.Round(Convert.ToDouble(txtPayableAmt.Value), txtPayableAmt.DecimalPlaces),
                PayableAmtOther = Math.Round(Convert.ToDouble(txtPayableAmtOther.Value), txtPayableAmtOther.DecimalPlaces),
                PaymentTerm = Convert.ToInt32(payTem),
                Period = Convert.ToInt32(txtPeriod.Text),
                PymtRef = txtPaymentRef.Text,
                ReceiptDate = txtReceivedDate.Value,
                Remark1 = txtRemark1.Text,
                Remark2 = txtRemark2.Text,
                Remark3 = txtRemark3.Text,
                ReturnedDate = txtReturnedDate.Value,
                VAT = Math.Round(Convert.ToDouble(txtVAT.Value), txtVAT.DecimalPlaces),
                VATOther = Math.Round(Convert.ToDouble(txtVATOther.Value), txtVATOther.DecimalPlaces),
                VATPercent = Math.Round(Convert.ToDouble(txtVATper.Value), txtVATper.DecimalPlaces),
                VendorCode = cboVendor.Value.ToString()

            };

            return info;

        }

        private void LoadTotalInv()
        {
            if (txtReference.Text != "")
            {
                BUS.InvoiceRegisterControl ctr = new InvoiceRegisterControl();
                DataTable dt = ctr.getTotalAmts(GetMainForm().PODInfo.Business_ID, Convert.ToInt32(txtReference.Text), ref sErr);
                if (dt.Rows.Count == 1 && sErr == "")
                {
                    txtRefPayableAmt.Value = Convert.ToDecimal(dt.Rows[0]["PayableAmt"]);
                    txtRefPayableAmtOther.Value = Convert.ToDecimal(dt.Rows[0]["PayableAmtOther"]);
                    txtRefVATPayableAmt.Value = Convert.ToDecimal(dt.Rows[0]["VAT"]);
                }
            }

        }
        private void LoadTotalBudget()
        {
            if (cboBudgetCode.SelectedValue != null)
            {
                BUS.BudgetsControl ctr = new BudgetsControl();
                BUS.InvoiceRegisterControl ctrIRG = new InvoiceRegisterControl();

                DataTable dt = ctr.getTotalAmts(GetMainForm().PODInfo.Business_ID, cboBudgetCode.SelectedValue + "", Convert.ToInt32(txtYear.Value), ref sErr);
                if (dt.Rows.Count == 1 && sErr == "")
                {
                    txtBudgetApproved.Value = Convert.ToDecimal(dt.Rows[0]["LimitAmt"]);
                    txtRemainingBudget.Value = txtBudgetApproved.Value - ctrIRG.getBudgetTotalAmt(GetMainForm().PODInfo.Business_ID, cboBudgetCode.SelectedValue + "", Convert.ToInt32(txtYear.Value), ref sErr);
                }
            }
            else
            {
                txtBudgetApproved.Value = 0;
                txtRemainingBudget.Value = 0;
            }

        }
        private void LoadTotalContract()
        {
            string sErr = "";
            if (cboContractPO.Value.ToString() != "")
            {
                BUS.ContractControl ctr = new ContractControl();
                DataTable dt = ctr.getTotalAmts(GetMainForm().PODInfo.Business_ID, cboContractPO.Value.ToString(), ref sErr);

                if (dt.Rows.Count == 1 && sErr == "")
                {
                    txtContractValue.Value = Convert.ToDecimal(dt.Rows[0]["LimitAmt"]);
                    txtRemainingAmt.Value = Convert.ToDecimal(dt.Rows[0]["RemainingAmt"]);
                    txtShareContract.Value = Convert.ToDecimal(dt.Rows[0]["SharedAmt"]);
                    txtShareRemaining.Value = Convert.ToDecimal(dt.Rows[0]["SharedRemaining"]);
                }
            }
            else
            {
                txtContractValue.Value = 0;
                txtRemainingAmt.Value = 0;
                txtShareContract.Value = 0;
                txtShareRemaining.Value = 0;
            }

        }

        private void ShowUpdate()
        {
            DataTable dt = dgvInvoiceRegister.DataSource as DataTable;
            if (dt == null)
            {
                dt = ((BindingSource)dgvInvoiceRegister.DataSource).DataSource as DataTable;
            }
            InvoiceUpdate frm = new InvoiceUpdate(_strType, dt, GetMainForm());
            frm.FormClosed += (form, frmArgs) =>
            {
                VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
                if (((InvoiceUpdate)form).DialogResult == DialogResult.OK)
                {
                    reloadList();
                    if (txtReference.Text != "") selectRecord();
                }
            };
            frm.ShowDialog();
        }
        private void ShowSplit()
        {
            sErr = "";
            if (txtReference.Text == "")
            {
                MessageBox.Show("DO NOT delete blank invoice!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                return;
            }
            DTO.InvoiceRegisterInfo inf = GetData();
            InvoiceSplit spl = new InvoiceSplit(GetMainForm(), inf);
            spl.FormClosed += (form, frmArgs) =>
            {
                VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
                if (((InvoiceSplit)form).DialogResult == DialogResult.OK)
                {
                    var lContract = ((InvoiceSplit)form).contractChanged;
                    foreach (var co in lContract)
                    {
                        UpdateTotalContract(co);
                    }
                    reloadList();
                }

            };
            spl.ShowDialog();

        }
        private void ShowReturn()
        {
            InvoiceTransmit itrm = new InvoiceTransmit((DataTable)bisInvoiceRegister.DataSource, GetMainForm(), "R");
            itrm.FormClosed += (form, frmArgs) =>
            {
                if (((InvoiceTransmit)form).DialogResult == DialogResult.OK) reloadList();
            };
            itrm.ShowDialog();
        }
        private void ShowTranmit()
        {
            InvoiceTransmit itrm = new InvoiceTransmit((DataTable)bisInvoiceRegister.DataSource, GetMainForm(), "T");
            itrm.FormClosed += (form, frmArgs) =>
            {
                VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
                if (((InvoiceTransmit)form).DialogResult == DialogResult.OK) reloadList();

            };
            itrm.ShowDialog();
        }

        private void CheckPayRef()
        {
            if (string.IsNullOrEmpty(txtPaymentRef.Text) && !string.IsNullOrEmpty(txtPaymentDate.Text)) errProvider.SetError(txtPaymentRef, "Payment Ref cannot be blank if Payment Date exists, please check!");
            else if (!string.IsNullOrEmpty(txtPaymentRef.Text) && string.IsNullOrEmpty(txtPaymentDate.Text)) errProvider.SetError(txtPaymentRef, "Payment Date cannot be blank if Payment Ref exists, please check!");
            else errProvider.SetError(txtPaymentRef, "");
        }
        private void CheckInvNo()
        {
            if (txtInvNo.Text.Trim() == "")
            {
                errProvider.SetError(txtInvNo, "Invoice No. cannot blank, please check!");
            }
            else
            {
                Int16 line = txtLineNo.Text == "" ? Convert.ToInt16(-1) : Convert.ToInt16(txtLineNo.Text);
                int refer = txtReference.Text == "" ? Convert.ToInt32(-1) : Convert.ToInt32(txtReference.Text);
                BUS.InvoiceRegisterControl ctr = new InvoiceRegisterControl();
                if (GetMainForm().PODInfo.Business_ID == "HL")
                {
                    if (ctr.IsExistInvoiceNo(txtInvNo.Text, refer, cboCreditor.Text))
                    {
                        errProvider.SetError(txtInvNo, string.Format("Invoice No. {0}  already exists, please check!", txtInvNo.Text));
                    }
                    else errProvider.SetError(txtInvNo, "");
                }
                else
                {
                    if (ctr.IsExistInvoiceNo1(txtInvNo.Text, refer, cboCreditor.Text))
                    {
                        errProvider.SetError(txtInvNo, string.Format("Invoice No. {0}  already exists, please check!", txtInvNo.Text));
                    }
                    else errProvider.SetError(txtInvNo, "");
                }
            }
        }
        private void CheckVendorType()
        {

            if (cboVendorType.SelectedValue + "" == "" || cboVendorType.SelectedValue + "" == "O")
            {
                if (cboVendorType.SelectedValue == null) errProvider.SetError(cboVendorType, "Vendor Type cannot be blank, please check!!");
                else if (cboVendorType.SelectedValue.ToString().Trim() == "O") errProvider.SetError(cboVendorType, "Vendor Type should be Domestic or Foreigner, please check!");
                else errProvider.SetError(cboVendorType, "Vendor Type cannot be blank, please check!!");
            }
            else errProvider.SetError(cboVendorType, "");
        }
        private void CheckContractCode()
        {
            string sErr = "";
            cboContractPO.Tag = null;

            if (!string.IsNullOrEmpty(cboContractPO.Text) && cboContractPO.Text != cboContractPO.Value.ToString())
            {
                sErr = "This contract is not in list, please check!";
                cboContractPO.Tag = "Error";
                //errProvider.SetError(cboContractPO, );
            }
            if (cboContractPO.SelectedItem != null && ((DataRowView)cboContractPO.SelectedItem)["ExpiryDate"] != DBNull.Value && Convert.ToDateTime(((DataRowView)cboContractPO.SelectedItem)["ExpiryDate"]) < txtReceivedDate.Value)
            {
                string tmp = string.Format("This contract is overdue {0} day(s), please check!", (txtReceivedDate.Value - Convert.ToDateTime(((DataRowView)cboContractPO.SelectedItem)["ExpiryDate"])).TotalDays);
                if (sErr != "") sErr += "\nWarning: ";
                sErr += tmp;
                if (cboContractPO.Tag == null) cboContractPO.Tag = "Warning";
                //warnProvider.SetError(cboContractPO, erro);
            }
            errProvider.SetError(cboContractPO, sErr);

        }
        private void CheckCurrency()
        {
            if ((txtCurrency.Text == "" || txtCurrency.Text == "USD") && txtOtherAmount.Value > 0)
            {
                if (txtCurrency.Text == "") errProvider.SetError(txtCurrency, "Currency cannot be blank if Other Amount exists, please check!");
                else errProvider.SetError(txtCurrency, "Currency cannot be USD if Other Amount exists, please check!");
            }
            else errProvider.SetError(txtCurrency, "");

            if (txtOtherAmount.Value == 0 && txtCurrency.Text != "" && txtCurrency.Text != "USD")
                errProvider.SetError(txtOtherAmount, " Other Amount cannot be blank if Currency exists, please check!");
            else errProvider.SetError(txtOtherAmount, "");

            if (txtVAT.Value != 0 && txtVATOther.Value == 0 && txtCurrency.Text != "" && txtCurrency.Text != "USD")
                errProvider.SetError(txtVATOther, " Other Amount cannot be blank if Currency exists, please check!");
            else errProvider.SetError(txtVATOther, "");
        }
        private void CheckOurRef()
        {
            if (txtAccRef.Text != "")
            {
                if (txtAccRef.Text.Length > 10) errProvider.SetError(txtAccRef, "Our Ref should not exceeds 10 characters, please check!");
                else if (_processStatus == "O" || _processStatus == "C")
                {
                    if (CheckInSun(txtAccRef.Text, GetMainForm().PODInfo.Business_ID)) errProvider.SetError(txtAccRef, "Our Ref. already exists in SunSystems!");
                    else if (CheckInInvoice(txtAccRef.Text, GetMainForm().PODInfo.Business_ID)) errProvider.SetError(txtAccRef, "Our Ref. already exists in Invoice Register!");
                    else if (CheckInExpenseClaim(txtAccRef.Text, GetMainForm().PODInfo.Business_ID)) errProvider.SetError(txtAccRef, "Our Ref. already exists in Expense Claim!");
                    else errProvider.SetError(txtAccRef, "");
                }
                else
                {
                    if (IsOurRefModified())
                    {
                        if (CheckInSun(txtAccRef.Text, GetMainForm().PODInfo.Business_ID)) errProvider.SetError(txtAccRef, "Our Ref. already exists in SunSystems!");
                        else if (CheckInInvoice(txtAccRef.Text, GetMainForm().PODInfo.Business_ID)) errProvider.SetError(txtAccRef, "Our Ref. already exists in Invoice Register!");
                        else if (CheckInExpenseClaim(txtAccRef.Text, GetMainForm().PODInfo.Business_ID)) errProvider.SetError(txtAccRef, "Our Ref. already exists in Expense Claim!");
                        else errProvider.SetError(txtAccRef, "");
                    }
                    else errProvider.SetError(txtAccRef, "");
                }
            }
            else errProvider.SetError(txtAccRef, "");
        }
        private bool IsOurRefModified()
        {
            BUS.InvoiceRegisterControl ctr = new InvoiceRegisterControl();
            return ctr.IsOurRefModified(GetMainForm().PODInfo.Business_ID, Convert.ToInt32(txtReference.Text), Convert.ToInt32(txtLineNo.Text), txtAccRef.Text);
        }
        private bool CheckInExpenseClaim(string ourRef, string BusID)
        {
            BUS.InvoiceRegisterControl ctr = new InvoiceRegisterControl();

            return ctr.IsExistInExpenseClaim(ourRef, BusID);
        }
        private bool CheckInInvoice(string ourRef, string BusID)
        {
            BUS.InvoiceRegisterControl ctr = new InvoiceRegisterControl();
            if (BusID == "HL") return ctr.IsExist_InvoiceRegisterOurRef(ourRef);
            else return ctr.IsExist_InvoiceRegisterOurRef1(ourRef);
        }
        private bool CheckInSun(string ourRef, string BusID)
        {
            BUS.InvoiceRegisterControl ctr = new InvoiceRegisterControl();
            string connectString = MainForm.HLConnect;
            string db = GetMainForm().SUNDB;

            return ctr.IsExistInSun(ourRef, connectString, db);
        }
        private void CheckPayableAmt()
        {
            if (Math.Abs(txtPayableAmt.Value) > (decimal)1.3 * Math.Abs(txtExpenseAmt.Value) && txtPayableAmt.Value != 0)
                errProvider.SetError(txtPayableAmt, "Payable amount is not correct, please check again!");

            else errProvider.SetError(txtPayableAmt, "");
        }

        private void CheckValue()
        {
            txtAmount.Tag = null;
            errProvider.SetError(txtAmount, "");
            string code = cboContractPO.Value.ToString();
            if (code == "") return;
            string sErr = "";
            BUS.InvoiceRegisterControl ctr = new InvoiceRegisterControl();
            string otherBusId = GetMainForm().PODInfo.Business_ID == "HL" ? "HV" : "HL";
            int refer = txtReference.Text == "" ? -1 : Convert.ToInt32(txtReference.Text);
            int line = txtLineNo.Text == "" ? 1 : Convert.ToInt32(txtLineNo.Text);
            string sErr1 = "";
            decimal totalCurrentAmt = ctr.getContractTotalAmt(GetMainForm().PODInfo.Business_ID, code, ref sErr1, refer, line);
            sErr += sErr1;
            decimal totalOtherAmt = ctr.getContractTotalAmt(otherBusId, code, ref sErr1);
            sErr += sErr1;
            BUS.ContractControl ctrContract = new ContractControl();
            decimal totalCurrentContractAmt = ctrContract.getTotalAmt(GetMainForm().PODInfo.Business_ID, code, ref sErr);
            decimal totalOtherContractAmt = ctrContract.getTotalAmt(otherBusId, code, ref sErr);
            if (!chkUncheckI.Checked) //if (cboContractPO.SelectedItem is DataRowView) chkUncheckI.Checked = ((DataRowView)cboContractPO.SelectedItem)["SharedContract"].ToString() != "0";
            {
                if (totalCurrentAmt + txtAmount.Value + totalOtherAmt > totalCurrentContractAmt + totalOtherContractAmt)
                {
                    sErr = string.Format("The total contract is overpaid {0:N2}. Please check!", totalCurrentAmt + txtAmount.Value + totalOtherAmt - (totalCurrentContractAmt + totalOtherContractAmt));
                    txtAmount.Tag = "Error";
                    //    errProvider.SetError(txtAmount,sErr);
                }
                else if ((totalCurrentAmt + txtAmount.Value) > totalCurrentContractAmt)
                {
                    if (txtAmount.Tag == null) txtAmount.Tag = "Warning";
                    sErr = string.Format("The total contract is overpaid {0:N2}. The total shared contract value is not over through!", (totalCurrentAmt + txtAmount.Value) - totalCurrentContractAmt);
                    // warnProvider.SetError(txtAmount, sErr);
                }
                else if (totalCurrentContractAmt != 0 && (totalCurrentAmt + txtAmount.Value) / totalCurrentContractAmt > Convert.ToDecimal(0.75))
                {
                    if (txtAmount.Tag == null) txtAmount.Tag = "Warning";
                    sErr = string.Format("Invoice amount is occupied over 75% of contract value", (totalCurrentAmt + txtAmount.Value) - totalCurrentContractAmt);
                    // warnProvider.SetError(txtAmount, sErr);
                }
            }
            /*
             * Check budget value *
            code = cboBudgetCode.SelectedValue + "";
            int year = Convert.ToInt32(txtYear.Value);

            if (!string.IsNullOrEmpty(code))
            {
                totalCurrentAmt = ctr.getBudgetTotalAmt(GetMainForm().PODInfo.Business_ID, code, year, ref sErr1, refer, line);
                sErr += sErr1 + "";
                totalOtherAmt = ctr.getBudgetTotalAmt(otherBusId, code, year, ref sErr1);
                sErr += sErr1 + "";
                BUS.BudgetsControl ctrBudget = new BudgetsControl();
                decimal totalCurrentBudgetAmt = ctrBudget.getTotalAmt(GetMainForm().PODInfo.Business_ID, code, year, ref sErr1);
                sErr += sErr1 + "";
                decimal totalOtherBudgetAmt = ctrBudget.getTotalAmt(otherBusId, code, year, ref sErr1);
                sErr += sErr1 + "";
                if (chkShared.Checked) //if (cboContractPO.SelectedItem is DataRowView) chkUncheckI.Checked = ((DataRowView)cboContractPO.SelectedItem)["SharedContract"].ToString() != "0";
                {
                    if (totalCurrentAmt + txtAmount.Value + totalOtherAmt > totalCurrentBudgetAmt + totalOtherBudgetAmt)
                    {
                        string tmp = string.Format("The total Budget is overpaid {0:N2}. Please check!", totalCurrentAmt + txtAmount.Value + totalOtherAmt - (totalCurrentBudgetAmt + totalOtherBudgetAmt));
                        if (sErr != "") sErr += "\nError: ";
                        sErr += tmp;
                        txtAmount.Tag = "Error";
                    }
                    else if ((totalCurrentAmt + txtAmount.Value) > totalCurrentBudgetAmt)
                    {
                        if (txtAmount.Tag == null) txtAmount.Tag = "Warning";
                        string tmp = string.Format("The total Budget is overpaid {0:N2}. The total shared Budget value is not over through!", totalCurrentAmt + txtAmount.Value - totalCurrentBudgetAmt);
                        if (sErr != "") sErr += "\nWarning: ";
                        sErr += tmp;
                    }
                }
                else
                {
                    if (totalCurrentAmt + txtAmount.Value > totalCurrentBudgetAmt)
                    {
                        string tmp = string.Format("The Budget contract is overpaid {0:N2}. Please check!", totalCurrentAmt + txtAmount.Value - totalCurrentBudgetAmt);
                        txtAmount.Tag = "Error";
                        if (sErr != "") sErr += "\nError: ";
                        sErr += tmp;
                    }

                }
            }
            */

            errProvider.SetError(txtAmount, sErr);
        }


        private void CheckBudgetCode()
        {
            if (!string.IsNullOrEmpty(cboBudgetCode.Text) && cboBudgetCode.SelectedValue == null)
            {
                errProvider.SetError(cboBudgetCode, "Budget Code is not in list! please check");
                return;
            }
            else errProvider.SetError(cboBudgetCode, "");
        }

        private void CheckIssueDate()
        {
            if (txtIssuedDate.Text == "") errProvider.SetError(txtIssuedDate, " Issue Date cannot be blank!");

            else errProvider.SetError(txtIssuedDate, "");
        }
        private void CheckReceiDate()
        {
            DateTime reciveDate = txtReceivedDate.Value;
            BUS.InvoiceRegisterControl ctr = new InvoiceRegisterControl();
            if ((_processStatus == "C" || _processStatus == "O") && !ctr.IsValidPeriod(reciveDate.Year * 1000 + reciveDate.Month)) errProvider.SetError(txtReceivedDate, "Check Receive Date, please!");
            else errProvider.SetError(txtReceivedDate, "");
        }
        private void CheckVendorCode()
        {
            if (cboVendor.Value.ToString() != cboVendor.Text) errProvider.SetError(cboVendor, "Field Vendor Code is not in list! Please check!");

            else if (cboVendor.Value.ToString() == "") errProvider.SetError(cboVendor, "Field Vendor Code is blank! Please check!");

            else errProvider.SetError(cboVendor, "");
        }

        private void UpdateTotalBudget()
        {
            //if (cboBudgetCode.Value.ToString() != "")
            //{
            //    //BUS.BudgetsControl ctr = new BudgetsControl();
            //    //string sErr = ctr.updateTotal(GetMainForm().PODInfo.Business_ID, cboBudgetCode.Value.ToString());
            //}
        }
        private void UpdateTotalContract(string contractCode = null)
        {
            if (string.IsNullOrEmpty(contractCode)) contractCode = cboContractPO.Value.ToString();
            if (!string.IsNullOrEmpty(contractCode))
            {
                BUS.ContractControl ctr = new ContractControl();
                string sErr = ctr.updateTotal(GetMainForm().PODInfo.Business_ID, contractCode);
            }
        }
        private void UpdatePayableValue(Control source = null)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            gbPrimary.SuspendLayout();
            if (cboVendorType.SelectedValue != null && cboVendorType.SelectedValue.ToString() == "D")
            {
                txtPayableAmt.Value = txtAmount.Value + txtVAT.Value;
                txtPayableAmtOther.Value = txtOtherAmount.Value + txtVATOther.Value;
            }
            else
            {
                txtPayableAmt.Value = txtAmount.Value;
                txtPayableAmtOther.Value = txtOtherAmount.Value;
            }

            if (cboVendorType.SelectedValue != null && cboVendorType.SelectedValue.ToString() == "F") txtExpenseAmt.Value = txtAmount.Value + txtCIT.Value;
            else txtExpenseAmt.Value = txtAmount.Value;
            gbPrimary.ResumeLayout(true);
        }

        private void cboCreditor_SelectedValueChanged(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (cboCreditor.SelectedItem is DataRowView && cboCreditor.Focus() == true) cboVendor.Value = ((DataRowView)cboCreditor.SelectedItem)["VendorCode"].ToString();

        }

        private void cboContractPO_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cboContractPO.SelectedItem is DataRowView) chkUncheckI.Checked = ((DataRowView)cboContractPO.SelectedItem)["SharedContract"].ToString() != "0";
            if (cboContractPO.SelectedItem is DataRowView) txtPaymTerm.Text = ((DataRowView)cboContractPO.SelectedItem)["PaymentTerm"].ToString();
            if (cboContractPO.SelectedItem is DataRowView) cboBudgetCode.SelectedValue = ((DataRowView)cboContractPO.SelectedItem)["BudgetCode"].ToString();
            if (cboContractPO.SelectedItem is DataRowView) txtYear.Value = ((DataRowView)cboContractPO.SelectedItem)["BudgetYear"] == DBNull.Value ? 0 : Convert.ToInt32(((DataRowView)cboContractPO.SelectedItem)["BudgetYear"]);

            DataTable dt = btBudget.Tag as DataTable;
            if (dt != null)
            {
                DataRow[] arrRow = dt.Select("BudgetCode = '" + cboBudgetCode.SelectedValue + "' AND Year = " + txtYear.Value);
                if (arrRow.Length > 0)
                {
                    chkShared.Checked = arrRow[0]["isShared"].ToString() == "1";
                }
            }

        }

        private void txtOtherAmount_ValueChanged(object sender, EventArgs e)
        {
            if (_isCalculate)
            {
                _isCalculate = false;
                if (txtRate.Value != 0) txtAmount.Value = txtOtherAmount.Value / txtRate.Value;
                txtVAT.Value = txtAmount.Value * (txtVATper.Value / 100);
                txtVATOther.Value = txtOtherAmount.Value * (txtVATper.Value / 100);
                UpdatePayableValue(txtOtherAmount);
                _isCalculate = true;
            }


        }

        private void txtCurrency_TextChanged(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (_isCalculate)
            {
                _isCalculate = false;
                gbPrimary.SuspendLayout();
                BUS.InvoiceRegisterControl ctr = new InvoiceRegisterControl();
                txtRate.Value = ctr.getConvRate(GetMainForm().PODInfo.Business_ID, DateTime.Today, ref sErr);

                if (txtRate.Value == 0) txtAmount.Value = 0;
                else txtAmount.Value = txtOtherAmount.Value / txtRate.Value;
                gbPrimary.ResumeLayout(true);

                UpdatePayableValue(txtCurrency);

                _isCalculate = true;
            }
        }

        private void txtVATOther_ValueChanged(object sender, EventArgs e)
        {
            if (_isCalculate)
            {
                _isCalculate = false;
                UpdatePayableValue(txtVATOther);
                _isCalculate = true;
            }
        }

        private void txtReceivedDate_OnTextChange(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (_isCalculate)
            {
                _isCalculate = false;
                if (txtReceivedDate.Text.Trim() != "")
                {
                    try
                    {
                        DateTime reciveDate = txtReceivedDate.Value;// DateTime.ParseExact(, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
                        if (Regex.IsMatch(txtPaymTerm.Text, "^[0-9]+$")) txtDueDate.Text = reciveDate.AddDays(Convert.ToInt32(txtPaymTerm.Text)).ToString("dd/MM/yyyy");
                        //if (Regex.IsMatch(txtPaymTerm.Text, "^[0-9]+$")) txtDueDate.Text = reciveDate.AddDays(Convert.ToInt32(txtPaymTerm.Text)).ToString("dd/MM/yyyy");
                        if (_processStatus == "C" || _processStatus == "O") txtPeriod.Text = reciveDate.ToString("yyyy0MM");

                    }
                    catch (Exception ex)
                    {
                        sErr = ex.Message;
                        //errProvider.SetError(txtReceivedDate, "Invalide format datetime");
                    }
                }
                _isCalculate = true;
            }
        }

        private void cboVendor_SelectedValueChanged(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (cboVendor.SelectedItem is DataRowView)
            {
                cboCreditor.Text = ((DataRowView)cboVendor.SelectedItem)["VendorName"].ToString();
                cboCreditor.Focus();
            }
            //CheckVendorCode();
        }

        private void txtCIT_ValueChanged(object sender, EventArgs e)
        {
            if (_isCalculate)
            {
                _isCalculate = false;
                UpdatePayableValue(txtCIT);
                _isCalculate = true;
            }
        }

        private void txtRate_ValueChanged(object sender, EventArgs e)
        {
            if (_isCalculate)
            {
                _isCalculate = false;
                gbPrimary.SuspendLayout();
                if (txtRate.Value == 0) txtAmount.Value = 0;
                else txtAmount.Value = txtOtherAmount.Value / txtRate.Value;

                txtVAT.Value = txtAmount.Value * (txtVATper.Value / 100);
                txtVATOther.Value = txtOtherAmount.Value * (txtVATper.Value / 100);

                gbPrimary.ResumeLayout(true);
                UpdatePayableValue(txtRate);
                _isCalculate = true;
                //gbPrimary.Focus();
                txtAmount.Focus();
            }
        }

        private void txtAmount_ValueChanged(object sender, EventArgs e)
        {
            if (_isCalculate)
            {
                _isCalculate = false;

                if (txtAmount.Value == 0) txtRate.Value = 0;
                else txtRate.Value = txtOtherAmount.Value / txtAmount.Value;
                txtVAT.Value = txtAmount.Value * (txtVATper.Value / 100);
                txtVATOther.Value = txtOtherAmount.Value * (txtVATper.Value / 100);

                UpdatePayableValue(txtAmount);
                _isCalculate = true;
            }
        }

        private void txtVATper_ValueChanged(object sender, EventArgs e)
        {
            if (_isCalculate)
            {
                _isCalculate = false;
                txtVAT.Value = txtAmount.Value * (txtVATper.Value / 100);
                txtVATOther.Value = txtOtherAmount.Value * (txtVATper.Value / 100);
                UpdatePayableValue(txtVATper);
                _isCalculate = true;
            }
        }

        private void txtPaymTerm_TextChanged_1(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (_isCalculate)
            {
                _isCalculate = false;
                DateTime reciveDate = txtReceivedDate.Value;
                if (Regex.IsMatch(txtPaymTerm.Text, "^[0-9]+$")) txtDueDate.Text = reciveDate.AddDays(Convert.ToInt32(txtPaymTerm.Text)).ToString("dd/MM/yyyy");
                UpdatePayableValue(txtPaymTerm);
                _isCalculate = true;
            }
        }

        private void txtVAT_ValueChanged(object sender, EventArgs e)
        {
            if (_isCalculate)
            {
                _isCalculate = false;
                UpdatePayableValue(txtVAT);
                _isCalculate = true;
            }
        }

        //private void txtOtherAmount_Enter(object sender, EventArgs e)
        //{
        //    (sender as NumericUpDown).Select(0, (sender as NumericUpDown).ToString().Length);
        //}

        private void cboVendorType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboVendorType.SelectedValue != null && cboVendorType.SelectedValue.ToString() == "D") txtCIT.Value = 0;
            if (_isCalculate)
            {
                _isCalculate = false;
                UpdatePayableValue(cboVendorType);
                _isCalculate = true;
            }
        }

        private void btBudget_Click(object sender, EventArgs e)
        {
            ViewBudget();
        }

        private void ViewBudget()
        {
            Forms.frmView frm = new Forms.frmView("bgC", GetMainForm());
            DataTable dt = btBudget.Tag as DataTable;

            if (cboBudgetCode.Text != null && cboBudgetCode.Text != "")
            {
                frm.FilterRow = "  BudgetCode LIKE '" + cboBudgetCode.Text + "%'";
            }
            frm.DataSource = dt.Copy();
            frm.FormClosed += (form, args) =>
            {
                VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
                if (((Forms.frmView)form).DialogResult == DialogResult.OK)
                {
                    cboBudgetCode.SelectedValue = ((Forms.frmView)form).ReturnValue["BudgetCode"];
                    txtYear.Value = Convert.ToInt32(((Forms.frmView)form).ReturnValue["Year"]);
                }
                cboBudgetCode.Focus();
            };
            frm.ShowDialog();
        }

        private void cboContractPO_Leave(object sender, EventArgs e)
        {
            if (cboContractPO.Text != null && cboContractPO.Text.Trim() != "")
            {
                if (cboContractPO.Value.ToString().Trim() == "")
                {
                    cboContractPO.Focus();
                    MessageBox.Show(" Please select from the list ", false);
                }
            }
        }

        //private void cboCreditor_Leave(object sender, EventArgs e)
        //{
        //    if (cboCreditor.Text != null && cboCreditor.Text.Trim() != "")
        //    {
        //        if (cboCreditor.Value.ToString().Trim() == "")
        //        {
        //            cboCreditor.Focus();
        //            MessageBox.Show(" Please select from the list ", false);
        //        }
        //    }
        //}

        private void cboVendor_Leave(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (cboVendor.Text != null && cboVendor.Text.Trim() != "")
            {
                if (cboVendor.Value.ToString().Trim() == "")
                {
                    cboVendor.Focus();
                    MessageBox.Show(" Please select from the list ", false);
                }
            }
        }

        private void panel4_Click(object sender, EventArgs e)
        {

        }

        //private void cboBudgetCode_Leave(object sender, EventArgs e)
        //{
        //    if (cboBudgetCode.Text != null && cboBudgetCode.Text.Trim() != "")
        //    {
        //        ViewBudget();
        //        //if (cboBudgetCode.SelectedValue == null)
        //        //{
        //        //    cboBudgetCode.Focus();
        //        //    MessageBox.Show(" Please select from the list ", false);
        //        //}
        //    }
        //}


    }

}